<?php
if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function: 項目管理 產品分類
 *@param datetime 2012-02-15
 *@param author solgh
 ********************/
class Categorys extends Admins_Controller {

  private $data=array();
  private $unique_id;
  public function __construct(){
    parent::__construct();
    $this->data['currentPage']='manages';
    $this->load->model('categorys_mdl');
    //查詢語言
    $this->load->model('languages_mdl');
    $this->data['format_time']=$this->settings['default_time'];
    $this->data['languages']=$this->languages_mdl->get_core_languages(array('status'=>1));
    $data=array('language_id'=>$this->settings['default_language'],'parent_id'=>0,'status'=>1);
    $this->data['Categories']=$this->categorys_mdl->getCategories($data);
    $this->data['lang'] =$this->lang->language;
  }

  public function index(){
    $this->get_list();
    // $this->output->enable_profiler(TRUE);
    $this->load->view('admins/categorys_list_view',$this->data);
  }

  //獲取列表
  private function get_list(){
    $page = $this->input->get('p',TRUE);
    $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;
    $limit = $this->settings['default_admin_limit'];
    //$limit =1;
    $offset = ($page - 1) * $limit;
    if($offset < 0){
      redirect('admins/categorys');
    }
    $url_query=$_SERVER['QUERY_STRING'];
    // 保留查詢參數;
    $cookie = array(
        'name'   => 'url_query',
        'value'  => base64_encode($url_query),
        'expire' => '0',
        'path'   => '/',
    );
    $this->input->set_cookie($cookie);
    if(!empty($url_query)){
      $url_query=preg_replace('/&p=(\d+)/','',$url_query);
    }
    $this->data['title']=$this->input->get('title');
    $this->data['unique_url']=$this->input->get('unique_url');
    $this->data['field']=$this->input->get('field');
    $this->data['sort']=$this->input->get('sort');
    $this->data['field']=!empty($this->data['field'])?$this->data['field']:'n.sort_order';
    $this->data['sort']=!empty($this->data['sort'])?$this->data['sort']:'asc';

    $data=array(
      'language_id'=>$this->settings['default_language'],
      'parent_id'=>0,
      'limits'=>$limit,
      'offset'=>$offset
    );
    $data=!empty($this->data['title'])?array_merge($data,array('title'=>trim($this->data['title']))):$data;
    $data=!empty($this->data['unique_url'])?array_merge($data,array('unique_url'=>$this->data['unique_url'])):$data;

    $data=!empty($this->data['field'])?array_merge($data,array('field'=>$this->data['field'])):$data;
    $data=!empty($this->data['sort'])?array_merge($data,array('sort'=>strtoupper($this->data['sort']))):$data;

    $this->data['lists_count']=$this->categorys_mdl->totle_categorys($data);

    $pagination = '';
    if($this->data['lists_count'] > $limit)
    {
      $this->dpagination->currentPage($page);
      $this->dpagination->items($this->data['lists_count']);
      $this->dpagination->limit($limit);
      $this->dpagination->adjacents(5);
      $this->dpagination->target(site_url('admins/categorys').'?'.$url_query);
      $this->dpagination->parameterName('p');
      $this->dpagination->nextLabel($this->data['lang']['orders_lable_19']);
      $this->dpagination->PrevLabel($this->data['lang']['orders_lable_18']);
      $pagination = $this->dpagination->getOutput();
    }
    $this->data['pagination'] = $pagination;
    $this->data['lists']=$this->categorys_mdl->getCategories($data);
  }

  //添加按鈕頁面跳轉
  public function add(){
    $this->load->view('admins/categorys_form_view',$this->data);
  }

  //修改按鈕頁面跳轉
  public function edit($edit_id=0){
    if(!empty($edit_id)){
      //categorys信息
      $query=$this->categorys_mdl->get_categorys_by_id($edit_id);
      $this->data['edit_id']=$edit_id;
      $this->data['unique_url']=$query['unique_url'];
      $this->data['main_image']=$query['main_image'];
      $this->data['main_icon']=$query['main_icon'];
      $this->data['sort_order']=$query['sort_order'];
      $this->data['parent_id']=$query['parent_id'];
      $this->data['status']=$query['status'];
      $this->data['status']=$query['status'];

      //categorys資料 descriptions
      $results=$this->categorys_mdl->get_descriptions($edit_id);
      foreach($results->result_array() as $rs){
        $this->data['descriptions'][$rs['language_id']]=$rs;
      } //end foreach;
      $this->load->view('admins/categorys_form_view',$this->data);
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }

  //執行新增或修改
  public function modify(){
    $edit_id=$this->input->post('edit_id');
    $this->unique_id=$edit_id;
    $this->_load_validation_rules();
    if ($this->form_validation->run() == FALSE)
    {
      $this->data['thumb_img']=$this->input->post('thumb_img');
      $this->data['edit_id']=$edit_id;
      $this->data['error']=true;
      $this->load->view('admins/categorys_form_view',$this->data);
    }else{
//      $old_main_image=$this->input->post('old_main_image');
//      $main_image=$this->_upload_images('main_image',$old_main_image); //主圖片的上傳或修改.
      $data['general']=array(
        'unique_url'=>$this->input->post('unique_url'),
        'parent_id'=>$this->input->post('parent_id'),
        'sort_order'=>$this->input->post('sort_order'),
        'main_image'=>$this->input->post('main_image'),
        'main_icon'=>$this->input->post('main_icon'),
        'status'=>$this->input->post('status'),
      );

      //多語言描述
      $data['descriptions']=$this->input->post('descriptions');
      ////修改和添加.
      if(!empty($edit_id) && $edit_id>0){
        $operator_title='修改產品分類->'.$data['descriptions'][$this->settings['default_language']]['title'];
        $action='修改';
        $result=$this->categorys_mdl->edit_categorys($data,$edit_id);//修改
      }else{
        $operator_title='新增產品分類->'.$data['descriptions'][$this->settings['default_language']]['title'];
        $action='新增';
        $result=$this->categorys_mdl->add_categorys($data);//添加.
      }
      $this->operator_log($operator_title,$action,$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      $redirect=site_url('admins/categorys').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
    }
  }
  //上傳圖片.
  private function _upload_images($file_name='',$old_image=''){
    if(isset($_FILES[$file_name]['name']) && !empty($_FILES[$file_name]['name'])){
      $upload_path='uploads/categorys/';
      Imagelib::mkdir_file($upload_path); //創建路徑
      $allowed_types=array('jpg','png','gif','jpeg');
      $max_size='80240000';
      $temp_file=$_FILES[$file_name]['tmp_name']; //臨時文件
      $f_name=$_FILES[$file_name]['name'];
      $f_size=$_FILES[$file_name]['size'];
      $x = explode('.', $f_name);
      $f_extention=strtolower(end($x));
      if(!empty($f_extention) && in_array($f_extention,$allowed_types) && $f_size<=$max_size){
        $filename = md5(uniqid(mt_rand())).'.'.$f_extention; //新名字
        $product_file_name=$upload_path.$filename;
        if(move_uploaded_file($temp_file,$product_file_name)){
          if(!empty($old_file_name) && file_exists($old_file_name)){
            Imagelib::delete_image($old_image); //刪除舊圖片.
            Imagelib::delete_thumb_image($old_image); //刪除舊圖片縮略圖.
          }
          return $product_file_name; //返回上傳后的新名字.
        }
      }
    }else{
      return $old_image;
    }
  }

  //執行驗證
  public function _load_validation_rules(){
    // $this->form_validation->set_rules('unique_url','靜態URL','trim|alpha|is_unique[clickrcms_people_categorys.unique_url.id.'.$this->unique_id.']|max_length[20]');
    $this->form_validation->set_rules('sort_order','排序','required|trim|numeric|max_length[10]');
    $this->form_validation->set_rules('status','狀態','trim|required|numeric|max_length[1]');
    $this->form_validation->set_rules('parent_id','父類別','trim|required|numeric');
    $this->form_validation->set_rules('main_image','封面圖片','trim|max_length[100]');
    $this->form_validation->set_rules('main_icon','封面圖片','trim|max_length[100]');
    $this->form_validation->set_rules('edit_id','修改ID','trim|numeric');
    //多語言判斷
    foreach($this->data['languages']->result_array() as $lg){
      $title='descriptions['.$lg["id"].'][title]';
      $introduction='descriptions['.$lg["id"].'][introduction]';
      $content='descriptions['.$lg["id"].'][content]';
      $this->form_validation->set_rules($title,$lg['name'].' 產品分類名稱','trim|required|max_length[100]');
      $this->form_validation->set_rules($introduction,$lg['name'].' 類別簡介','trim|max_length[200]');
      $this->form_validation->set_rules($content,$lg['name'].' 類別內容','trim');
    }
  }
  //執行刪除功能
  public function delete($delete_id=0){
    if(!empty($delete_id)){
      $result=$this->categorys_mdl->delete_categorys($delete_id);
      $this->operator_log('刪除產品分類->ID:'.$delete_id,'刪除',$result);
      $msg = $result > 0?$this->data['lang']['global_lable_48']:$this->data['lang']['global_lable_49'];
      $notify = $result > 0?'success':'error';
      $this->nsession->set_flashdata($notify, $msg);
      $redirect=site_url('admins/categorys').$this->settings['url_query'];//獲取列表篩選參數
      redirect($redirect);
    }else{
      show_error('對不起,參數出錯!');
      exit;
    }
  }
}